package com.company;

import java.util.Arrays;

/**
 * @author zhangjian
 * @data 2023/3/19
 * @Version 1.0
 * @Descripion
 */
public class 排列组合 {
    public static void main(String[] args) {
        // 计算n的阶乘
        System.out.println(arrangement(3, 3));
        System.out.println(combination(3, 3));
        String[] a = {"a", "b", "c"};
        arrangementSelect(a, 3);
    }

    public static void arrangementSelect(String[] dataList, int n) {
       // System.out.println(String.format("A(%d, %d) = %d ", dataList.length, n, arrangement(n, dataList.length)));
        arrangementSelectRes(dataList, new String[n], 0);
    }

    private static void arrangementSelectRes(String[] dataList, String[] resultList, int resultIndex) {
        int resultLen = resultList.length;
        if (resultIndex >= resultLen) { // 全部选择完时，输出排列结果
            System.out.println(Arrays.asList(resultList));
            return;
        }
        // 递归选择下一个
        for (int i = 0; i < dataList.length; i++) {
            // 判断待选项是否存在于排列结果中
            boolean exists = false;
            for (int j = 0; j < resultIndex; j++) {
                if (dataList[i].equals(resultList[j])) {
                    exists = true;
                    break;
                }
            }
            if (!exists) { // 排列结果不存在该项，才可选择
                resultList[resultIndex] = dataList[i];
                arrangementSelectRes(dataList, resultList, resultIndex + 1);
            }
        }
    }



    /**
     * 计算排列A(n, m)
     *
     * @param m
     * @param n
     * @return 返回A(n, m)的排列个数
     */
    private static long arrangement(int m, int n) {
        return m <= n ? factorial(n) / factorial(n - m) : 0;
    }

    /**
     * 计算组合C(n, m)
     *
     * @param m
     * @param n
     * @return 返回C(n, m)的组合个数
     */
    private static long combination(int m, int n) {
        return m < n ? factorial(n) / (factorial(n - m) * factorial(m)) : 0;
    }

    /**
     * 计算n的阶乘
     *
     * @param n
     * @return 返回 n!
     */
    private static long factorial(int n) {
        long sum = 1;
        while (n > 0) {
            sum = sum * n--;
        }
        return sum;
    }
}
